var common = {};

/**
 * 001.关闭某个tab (通过id或者关闭当前) 并刷新上一个tab 默认会刷新
 * @param {Object} id: 即打开的标签上绑定的data-id="id"
 * @param {String} goId : 关闭tab后 激活哪个tab
 * 子页面 使用top.common.closeTab  或者parent.common.closeTab
 */
common.closeTab = function (id, refresh, goId) {
    var $tabs = $(document).data("multitabs") || parent.$(parent.document).data("multitabs");
    ;
    if (!$tabs) return;
    refresh = refresh === false ? false : true;
    var $navTab;
    var $navPanelList = $tabs.$element.navPanelList;
    if (id) {
        //参考源码中的 _exist 方法
        $navTab = $navPanelList.find('a[data-id="' + id + '"]:first');
    } else { //没有传入id则关闭当前激活的tab
        //参见源码中的active方法
        $navTab = $navPanelList.find('li.active:first a');
    }
    if (goId) { //激活某个id
        $navPanelList.find('a[data-id="' + goId + '"]:first').trigger("click");
    }
    $tabs.close($navTab);

    _refresh($navTab);

    //刷新某个li(激活的) 对应的tab
    function _refresh() {
        if (!refresh) return; // 不刷新则不管
        var $navTabRefresh = $("li.active a", $navPanelList);//获得当前激活的tab
        var iframeId = $navTabRefresh.attr("data-id");
        var param = $navTabRefresh.length ? $tabs._getParam($navTabRefresh) : {};
        var $tempTabPane = $(parent.document.getElementById(iframeId));
        if ($tempTabPane.is('iframe')) {
            $tempTabPane.attr('src', param.url);
        } else {
            $.ajax({
                url: param.url,
                dataType: "html",
                success: function (callback) {
                    $tempTabPane.html($navTabRefresh.options.content.ajax.success(callback));
                },
                error: function (callback) {
                    $tempTabPane.html($navTabRefresh.options.content.ajax.error(callback));
                }
            });
        }
    }
};
/**
 * 002. 在iframe内触发父document的Multitabs方法新建tab
 */
common.addTab = function (url, title, did) {
    did = did || common.convertUrl(url);
    parent.$(parent.document).data('multitabs').create({
        iframe: true, //指定为iframe模式，当值为false的时候，为智能模式，自动判断（内网用ajax，外网用iframe）。缺省为false。
        title: title, //标题（可选），没有则显示网址
        url: url, //链接（必须），如为外链，强制为info页
        did: did //指定生成的tab的id
    }, true);
}
/**
 * 003. 获取当前url中的全部参数
 */
common.getUrlParams = function () {
    var url = location.search; //获取url中"?"符后的字串
    var params = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            params[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return params;
}
/**
 * 004. 获取当前url中的指定的参数
 */
common.getUrlParam = function (key) {
    //构造一个含有目标参数的正则表达式对象
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    //匹配目标参数
    var r = window.location.search.substr(1).match(reg);
    //返回参数
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
}
/**
 * 005. 确认提示的按钮
 */
common.confirm = function (content, successFn, opts) {
    opts = opts || {};
    var options = {
        title: '确定',
        content: content,
        titleClass: '',
        type: 'green', //'default'' 'blue, green, red, orange, purple & dark'
        theme: 'bootstrap', //对话框的颜色主题，：'white', 'black', 'material' , 'bootstrap'
        buttons: {
            confirm: {
                text: '确定',
                btnClass: 'btn-red',
                action: successFn || $.noop()
            },
            cancle: {
                text: '取消',
                btnClass: 'btn-info',
                action: function () {
                }
            }
        }
    };
    $.confirm($.extend(true, {}, options, opts));
};

/**
 * 006. 是否是一个完整url
 */
common.isWholeUrl = function (url) {
    return url && /^(http|https|ftp):\/\/.*/.test(url);
};

/**
 * 007. 根据方法名调用方法
 */
common.callFunction = function (fnName, args) {
    try {
        var fn = eval(fnName);
        if (typeof fn == 'function') {
            fn.call(this, args);
        }
    } catch (e) {
        $.alert("根据方法名" + fnName + "调用方法错误:" + e);
        console.trace(e);
    }
};

common.getRandomLableClass = function (lableNumer) {
    if (!lableNumer) return;
    var labelClass = ['label label-primary', 'label label-success', 'label label-warning', 'label label-info',
        'label label-danger', 'label label-default'
    ];
    if (isNaN(lableNumer)) { //此处不再做额外的处理
        lableNumer = 0;
    }
    if (lableNumer === true) {
        lableNumer == 1;
    }
    if (lableNumer === false) {
        lableNumer == 0;
    }
    var index = lableNumer % 6;
    return labelClass[index];

}
/**
 * 009-根据后台返回的基本对象 弹出提示
 * @param {Object} result: BaseResponse
 */
common.alert = function (result, successFn, confirm) {
    if (!result || result.code === undefined) return;
    successFn = successFn || $.noop();
    if (result.code != 0) {
        $.alert({
            title: "请求失败",
            content: result.msg,
            onClose: function () {
                if (result.code == 401) {
                    top.location.href = project_prefix + "lcxm_login.html";
                }
            }
        });
    } else {
        if (confirm) {
            $.confirm({
                title: '',
                content: '操作成功',
                buttons: {
                    确认: function () {
                        successFn(result);
                    }
                }
            });
        } else {
            successFn(result);
        }


    }
};
/**
 * 去掉url中的特殊字符,把url转换成一个唯一标识id
 */
common.convertUrl = function (url) {
    if (!!url) {
        //deprecate 去掉参数 保证打开一个窗口url = url.substring(0, url.indexOf('?'));
        var u = url.replace(/[$#@&\\/\\?=.:<>\s]/g, '-');
        if (u && u.length > 64) {
            //保留前64位2
            u = u.substring(0, 64);
        }
        return u;
    }
    return null;
}


/*
sessionStorage：仅在当前浏览器窗口关闭前有效，自然也就不可能持久保持；
localStorage：始终有效，窗口或浏览器关闭也一直保存，
*/
var storage = {};
storage.set = function (key, data) {
    sessionStorage.setItem(key, JSON.stringify(data));
};
storage.get = function (key) {
    var data = sessionStorage.getItem(key);
    if (data) {
        return JSON.parse(data)
    }
    return "";
}
storage.remove = function (key) {
    sessionStorage.removeItem(key);
};
storage.clear = function () {
    sessionStorage.clear();
};

var $cache = {};
//根据id获取字典的值
$cache.getDict = function (id) {
    if (!id) return '';
    var key = "dict-" + id;
    var dictName = storage.get(key);
    if (dictName) return dictName;

    var dictNameUrl = "/system/dict/findDictName?id=" + id;
    $request.getSync(dictNameUrl, {}, function (result) {
        dictName = result.data;
        storage.set(key, dictName);
    });
    return dictName;
};

/********* for work report********************************/
//检测jira号是否存在
common.checkJiraCode = function (code, id) {
    let result = true;
    $.ajax({
        async: false,
        url: ctx + 'jira/checkCode',
        type: 'post',
        data: {
            code: code,
            id: id
        },
        success: function (data) {
            if (!data.data) {
                $.alert({
                    theme: 'bootstrap',
                    title: '温馨提示',
                    content: "jira号已存在"
                });
                result = false;
            }
        }
    });
    return result;
}
/**
 * 检测jira号是否存在于本系统和jira系统
 */
common.checkJiraExist = function (code) {
    let result = true;
    $.ajax({
        async: false,
        url: ctx + 'jira/exist',
        type: 'post',
        data: {
            code: code
        },
        success: function (res) {
            result = res.data;
        }
    });
    return result;
}


common.validateForm = function (formJson, ignoreFields) {
    ignoreFields = ignoreFields || ["id"];
    if (!formJson) return false;
    for (let k in formJson) {
        //不忽略的字段如果不存在 则返回false
        if (!ignoreFields.includes(k) && !formJson[k]) {
            return false
        }
    }
    return true;
}

common.reportTotalTime = function (projectId) {
    if (!projectId) return;
    $.ajax({
        async: false,
        url: ctx + 'report/totalTime/' + projectId,
        type: 'GET',
        success: function (res) {

            let day = (res.data / 480).toFixed(2);
            $.alert("当前项目已填报工时:<span style='color:red;'>" + res.data + "分钟(" + day + "人天</sapn>)");
        }
    });
}
/*
   导出当前查询条件下的日报数据
 */
common.exportReport = function (event) {
    let $btn = $(event);
    $btn.prop("disabled", true);
    let $form = $('form.lookup').clone().appendTo($("body"));
    let url = ctx + "report/export";
    $form.attr("method", "post").attr("action", url);
    $form.submit();
    $form.remove();
    setTimeout(function () {
        $btn.prop("disabled", false);
    }, 3000);

}

common.clickContent = function (e) {
    let title = $(e).attr("data-original-title");
    $.alert({
        theme: 'bootstrap',
        title: '工作内容',
        content: '<p style="white-space: pre-wrap">' + title + '</p>'
    });
}

/**
 * 初始化星期选择控件   daterangepicker.js    moment.min.js
 * @param id 日期input id                weekPicker
 * @param btnId 点击的按钮id               weekRangePicker
 * @param startId 星期开始时间 input id    startWeekDate
 * @param endId 星期结束时间 input id      endWeekDate
 * <div class="input-group">
 *     <input type="text" class="form-control input-sm" id="startWeekDate" name="startDate" readonly>
 *     <span class="input-group-addon">至</span>
 *     <input type="text" class="form-control input-sm" id="endWeekDate" name="endDate" readonly>
 *     <input type="text" id="weekPicker" class="form-control input-sm" style="display: none;"/>
 *      <span class="input-group-btn">
 *         <button class="btn btn-default input-sm" type="button" id="weekRangePicker"><i class="glyphicon glyphicon-calendar"></i></button>
 *       </span>
 * </div>
 */
common.initWeekDatePicker = function (id, btnId, startId, endId, parent,) {
    let parentEl = (!!parent) ? parent : 'body';
    console.info(parentEl);

    $('#' + id).daterangepicker({
        parentEl:parentEl,
        locale: {
            format: 'YYYY-MM-DD'
        },
        singleDatePicker: true,
        autoApply: true,
        showCustomRangeLabel: false,
        drops: 'right', // 控制弹出位置
        isInvalidDate: function (date) {
            // Disable selection of individual days
            return false;
        },
    }, function (start) {
        common.setWeekRange(start, startId, endId);
    });

    $('#weekPicker').on('apply.daterangepicker', function (ev, picker) {
        common.setWeekRange(picker.startDate, startId, endId);
    });

    // Set the initial value to the current week
    // common.setWeekRange(moment(), startId, endId);
    //点击按钮的时候 触发事件控件的点击事件
    $('#' + btnId).on("click", function () {
        debugger;
        $('#' + id).trigger("click");
    });

}
common.setWeekRange = function(date, startId, endId) {
    let scope = 'isoWeek'
    let startOfWeek = date.clone().startOf(scope);
    let endOfWeek = date.clone().endOf(scope);
    $('#' + startId).val(startOfWeek.format('YYYY-MM-DD'));
    $('#' + endId).val(endOfWeek.format('YYYY-MM-DD'));
    console.log("Selected  " + scope + ": " + startOfWeek.format('YYYY-MM-DD') + " to " + endOfWeek.format('YYYY-MM-DD'));

}


//一些共用的需要执行的js
$(document).ready(function (){
    common.reportInit();
});

common.reportInit= function(){
    //01. 点击可排序
    $("th.sortable").attr("title", "点击可排序");
};